package com.baway.zhangcaiping;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.baway.zhangcaiping.adapter.RecycleAdapter;
import com.baway.zhangcaiping.bean.Bean;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main2Activity extends AppCompatActivity {

    private RecyclerView demo_recycle;
    private SwipeRefreshLayout demo_swip;
    public static DisplayImageOptions options;
    ArrayList<Bean.ResultBean.RowsBean.InfoBean> list2=new ArrayList<Bean.ResultBean.RowsBean.InfoBean>();
    int count=11;
    int nn=3;
    private ArrayList<Bean.ResultBean.RowsBean.InfoBean> arr;
    private RecycleAdapter ada;
    int lastVisibleItem;
    private LinearLayoutManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        //创建DisplayImageOptions对象
        options = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();

        //初始化
        initView();

        //请求数据
        getData(count,nn);

        //下拉刷新
        demo_swip.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                list2.clear();
                getData(++count,++nn);
                demo_swip.setRefreshing(false);
                Toast.makeText(Main2Activity.this,"刷新成功",Toast.LENGTH_SHORT).show();

            }
        });

        //加载更多
       demo_recycle.setOnScrollListener(new RecyclerView.OnScrollListener() {
           @Override
           public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
               super.onScrollStateChanged(recyclerView, newState);
               if (newState ==RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 ==ada.getItemCount()){
                   getData(++count,++nn);

                   //吐司
                 Toast.makeText(Main2Activity.this,"添加新的数据",Toast.LENGTH_SHORT).show();
               }
           }

           @Override
           public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
               super.onScrolled(recyclerView, dx, dy);

               //得到最后一项
               lastVisibleItem=manager.findLastVisibleItemPosition();


           }
       });

    }
    //初始化
    private void initView() {

        //找控件
        demo_recycle = (RecyclerView) findViewById(R.id.demo_recycle);
        demo_swip = (SwipeRefreshLayout) findViewById(R.id.demo_swip);

        //管理器
        manager = new LinearLayoutManager(this);

        demo_recycle.setLayoutManager(manager);

        //这句就是添加我们自定义的分隔线
        demo_recycle.addItemDecoration(new MyDecoration(this, MyDecoration.VERTICAL_LIST));

    }

    //请求数据
    public void getData(int num,int cc)
    {
        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();
        //创建一个Request
        final Request request = new Request.Builder()
                .url("http://api.fang.anjuke.com/m/android/1.3/shouye/recInfosV3/?city_id=14&lat=40.04652&lng=116.306033&api_key=androidkey&sig=9317e9634b5fbc16078ab07abb6661c5&macid=45cd2478331b184ff0e15f29aaa89e3e&app=a-ajk&_pid=11738&o=PE-TL10-user+4.4.2+HuaweiPE-TL10+CHNC00B260+ota-rel-keys%2Crelease-keys&from=mobile&m=Android-PE-TL10&cv=9.5.1&cid=14&i=864601026706713&v=4.4.2&pm=b61&uuid=1848c59c-185d-48d9-b0e9-782016041109&_chat_id=0&qtime=201604"+num+"09160"+cc+"")
                .build();
         //new call
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Request request, IOException e)
            {

            }

            @Override
            public void onResponse(final Response response) throws IOException
            {
                final String htmlStr =  response.body().string();

                //主线程
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        //创建Gson对象
                        Gson gson=new Gson();
                        arr = new ArrayList<>();
                        //转化bean对象
                        Bean bean = gson.fromJson(htmlStr, Bean.class);

                        List<Bean.ResultBean.RowsBean> list = bean.result.rows;
                        for(Bean.ResultBean.RowsBean bb:list)
                        {
                            Bean.ResultBean.RowsBean.InfoBean info = bb.info;
                            arr.add(info);
                        }
                        //添加到集合中
                        list2.addAll(arr);

                        //判断
                        if(ada==null)
                        {
                            //设置适配器
                            ada = new RecycleAdapter(Main2Activity.this, list2);
                            demo_recycle.setAdapter(ada);
                        }else
                        {
                            //通知适配器刷新
                            ada.notifyDataSetChanged();
                        }

                        //Log.d("zzz",arr.toString());
                    }
                });
            }
        });
    }
}
